<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    *{margin: 0;padding: 0}
    body{
      display: flex;
      align-items: center;
      background: #fff;
    }
    canvas{
      box-shadow:3px 3px 3px rgba(50, 50, 50, 0.5);
      margin: 0 auto;
      margin-top: 200px;
      border: 1px solid #ddd;
      background: #fafafa;
    }
    button{
      padding:5px 10px;
      font-size:16px;
      color:#000;
      background: #ddd;
      margin-right: 180px;
    }

  </style>
</head>
<body>
  <canvas width="400" height="400" id="canvas"></canvas>
   <!-- <button id='back'>悔棋</button> -->
</body>
<script>
  //连接服务器
  var socket,userId;
  if(typeof(WebSocket) == "undefined") {
      alert("您的浏览器不支持WebSocket");
  }
  conn();
  function conn(){
  //实现化WebSocket对象，指定要连接的服务器地址与端口
      socket = new WebSocket("ws://127.0.0.1:8001");
      //打开事件
      socket.onopen = function() {
        let msg = `{"type":"0","msg":"用户进入"}`
           socket.send(msg);
      };
      //获得消息事件
      socket.onmessage = function(res) {
        console.log(res.data);
        let data = JSON.parse(res.data)
          console.log(data);
        if(data.type == 0){
          if(data.id){
            userId = data.id
          }
          alert(data.msg)
        }else{
          c.add(data.msg)
        }
      };
      //关闭事件
      socket.onclose = function() {
          alert("Socket已关闭");
      };
      //发生了错误事件
      socket.onerror = function() {
          alert("发生了错误");
      }
  };
</script>
<script>
  var canvas=document.getElementById("canvas");
  var cxt=canvas.getContext("2d");
  //var reback = document.getElementById('back')
  //棋盘
  var chessboard = {
    currrentUser : 0,
    drawBoard:function(){
      cxt.strokeStyle="#777";
      cxt.strokeRect(20,20,360,360);
      cxt.lineWidth = 1;
      cxt.strokeStyle="#999";
      for (let index = 50; index <= 360; index += 30) {
        cxt.strokeStyle="#666";

        cxt.beginPath();    
        cxt.moveTo(20,index);
        cxt.lineTo(380,index);
        cxt.stroke();
        cxt.closePath();

        cxt.beginPath();
        cxt.moveTo(index,20);
        cxt.lineTo(index,380);
        cxt.stroke();
        cxt.closePath();
      }
    },
    drawChess:function(chess){
      cxt.beginPath();
      cxt.strokeStyle = '#999';
      cxt.arc(chess.x * 30 +20,chess.y * 30 +20,12,Math.PI*2,0,true);
      cxt.stroke();
      cxt.closePath();
      var color = this.currrentUser == 0 ? '#111' :'#fff';
      cxt.fillStyle = color;
      cxt.fill();
      this.currrentUser = 1 - this.currrentUser;
    },
    registerClickEvent:function(){
      var boardLeft = canvas.offsetLeft + 20;
      var boardTop = canvas.offsetTop + 20;
      var self = this;
      canvas.addEventListener('click',function (e) {
        //点击点到棋盘左边的距离
        var left = e.x - boardLeft;
        var top = e.y - boardTop;
  
        //格子的长宽是30
        var x = Math.floor(left / 30);
        var y = Math.floor(top / 30);

        //判断点击离哪个点最近
        var lx = left % 30;
        var ly = top % 30;

        x = lx > 15 ? x + 1 : x;
        y = ly > 15 ? y + 1 : y;
        
        //画棋子
        var chess = {
          x:x,
          y:y
        }
        let sendData = {data:chess,id:userId,type:1}
        socket.send(JSON.stringify(sendData));
        c.add(chess);
        console.log('add')
      },false)
    },
    init:function(){
      this.drawBoard();
      this.registerClickEvent();
    }
  }

  //棋子
  var c = {
    list : [],
    paint:function(arr){
      arr.forEach(element => {
        cxt.beginPath();
        cxt.strokeStyle = '#999';
        cxt.arc(element.x * 30 +20,element.y * 30 +20,12,Math.PI*2,0,true);
        cxt.stroke();
        cxt.closePath();
        var color = element.type == 0 ? '#111' :'#fff';
        cxt.fillStyle = color;
        cxt.fill();
      });
    },
    add:function(target){
      target.type = chessboard.currrentUser;
      this.rule(target);
      if(this.list.length == 0){
          this.list.push(target);
          chessboard.drawChess(target);
      }else{
        var newlist = this.list.filter(item => {
          return item.x == target.x && item.y == target.y
      })
        if(newlist.length == 0){
          this.list.push(target);
          chessboard.drawChess(target);
        } 
      }  
      console.log('send')
      //socket.send(JSON.stringify(target))
    },
    line:function(target,vulue1,vulue2,val){
      //向左或者向上的数量(val = -1),向右或者向下的数量(val = 1)
     var num = 0;
     for (var i = target[vulue1];i >= 0;i=i+val) {
        var chess = this.list.filter(item=>{
           return item[vulue1] == i + val && item[vulue2] == target[vulue2] && item.type == chessboard.currrentUser ;
        })
        if (chess.length < 1) {
          break;
        }
         num ++ ;
      }
      return num ;
    },
    sloperightdown:function(target,vulue1,vulue2){
      //斜向右下的数量
     var num = 0;
     var a = target[vulue1];
     var b= target[vulue2];
     for (var i = 1;i < 5;i++) {
        var chess = this.list.filter(item=>{
           return item[vulue1] == i + a && item[vulue2] == b + i && item.type == chessboard.currrentUser;
        })
        if (chess.length < 1) {
          break;
        }
        num ++ ; 
      }
      return num ;
    },
    slopeleftup:function(target,vulue1,vulue2){
      //斜向左上的数量
     var num = 0;
     var a = target[vulue1];
     var b= target[vulue2];
     for (var i = -1;i > -5;i--) {
        var chess = this.list.filter(item=>{
           return item[vulue1] == i + a && item[vulue2] == b + i && item.type == chessboard.currrentUser;
        })
        if (chess.length < 1) {
          break;
        }
        num ++ ; 
      }
      return num ;
    },
    sloperightup:function(target,vulue1,vulue2){
      //斜向右上的数量
     var num = 0;
     var a = target[vulue1];
     var b= target[vulue2];
     for (var i = 1;i < 5;i++) {
        var chess = this.list.filter(item=>{
           return item[vulue1] == i + a && item[vulue2] == b - i && item.type == chessboard.currrentUser;
        })
        if (chess.length < 1) {
          break;
        }
        num ++ ; 
      }
      return num ;
    },
    slopeleftdown:function(target,vulue1,vulue2){
      //斜向左下的数量
     var num = 0;
     var a = target[vulue1];
     var b= target[vulue2];
     for (var i = 1;i < 5;i++) {
        var chess = this.list.filter(item=>{
           return item[vulue1] == a - i && item[vulue2] == b + i && item.type == chessboard.currrentUser;
        })
        if (chess.length < 1) {
          break;
        }
        num ++ ; 
      }
      return num ;
    },
    rule:function(target){
     var lxl = this.line(target,'x','y',-1);  //横向向左
     var lyr = this.line(target,'x','y',1);  //横向向右
     var cxu = this.line(target,'y','x',-1); //纵向向上
     var cyd = this.line(target,'y','x',1); //纵向向下
     var slu = this.slopeleftup(target,'x','y');  //斜向向左上
     var sld = this.slopeleftdown(target,'x','y');  //斜向向左下
     var sru = this.sloperightup(target,'x','y'); //斜向向右上
     var srd = this.sloperightdown(target,'x','y'); //斜向向右下
   
    if(lyr + lxl >= 4 || cyd + cxu >= 4 || sru + sld >= 4 || slu + srd >= 4 ){
        alert('你赢了')
      }
    },
  }
  // reback.addEventListener('click',function(){
  //    var len = c.list.length - 1;
  //    c.list = c.list.slice(0,len-1);
  //    cxt.clearRect(20,20,360,360);
  //    chessboard.init();
  //    c.paint(c.list)
  // })
  chessboard.init();
</script>

</html>